from datetime import datetime
from django.db import models
from ourcity.core.models import Profile
from django.core.mail import send_mass_mail

class EmailManager(models.Manager):
    def active(self):
        return self.filter(active=True)

class Email(models.Model):
    subject = models.CharField(max_length=300)
    body = models.TextField()
    send = models.BooleanField(default=False, help_text="Do you want to send this email upon saving?")
    create_date = models.DateTimeField(auto_now_add=True)

    objects = EmailManager()

    def save(self, *args, **kwargs):

        # get super class called 'Email' and call save on it
        super(Email, self).save(*args, **kwargs)

        if self.send:
            datalist = []
            for profile in Profile.objects.filter(email_opt_in=True):
                datalist.append((self.subject, self.body, 'info@ourphiladelphia.org', [profile.user.email]))
            send_mass_mail(datalist)

    # returned when viewed in admin list view
    def __unicode__(self):
        return self.subject
